package com.xiaoshuidi.cloud.module.finance.mq.consumer;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.xiaoshuidi.cloud.framework.common.core.KeyValue;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.common.util.json.JsonUtils;
import com.xiaoshuidi.cloud.framework.pay.core.client.PayClient;
import com.xiaoshuidi.cloud.framework.pay.core.client.PayClientFactory;
import com.xiaoshuidi.cloud.framework.pay.core.client.PayCommonResult;
import com.xiaoshuidi.cloud.framework.pay.core.client.dto.PayCloseUnifiedReqDTO;
import com.xiaoshuidi.cloud.framework.pay.core.client.dto.PayQueryUnifiedReqDTO;
import com.xiaoshuidi.cloud.framework.pay.core.client.dto.PayQueryUnifiedRespDTO;
import com.xiaoshuidi.cloud.framework.pay.core.enums.PayStatusEnum;
import com.xiaoshuidi.cloud.framework.tenant.core.util.TenantUtils;
import com.xiaoshuidi.cloud.module.finance.dal.dataobject.order.PayOrderDO;
import com.xiaoshuidi.cloud.module.finance.enums.order.FinanceCommonStatusEnum;
import com.xiaoshuidi.cloud.module.finance.mq.producer.CouponUnlockDelayProducer;
import com.xiaoshuidi.cloud.module.finance.service.order.PayOrderService;
import com.xiaoshuidi.cloud.module.member.api.coupon.CouponApi;
import com.xiaoshuidi.cloud.module.member.api.coupon.vo.CouponUnLockVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.function.Consumer;

@Slf4j
@Component("couponUnlockDelay")
public class CouponUnlockDelayConsumer implements Consumer<PayOrderDO> {
    @Resource
    private PayOrderService payOrderService;
    @Resource
    private PayClientFactory payClientFactory;
    @Resource
    private CouponApi couponApi;
    @Resource
    private CouponUnlockDelayProducer couponUnlockDelayProducer;


    @Override
    public void accept(PayOrderDO payOrder) {
        if (payOrder.getId() == null) {
            return;
        }
        log.info("优惠券解锁{}", payOrder.getId());
        PayOrderDO order = TenantUtils.executeIgnoreAndReturn(() -> payOrderService.getOrder(payOrder.getId()));
        if (order != null && FinanceCommonStatusEnum.WAITING.name().equals(order.getStatus())
                && StringUtils.hasText(order.getMerchantOrderId()) && !CollectionUtils.isEmpty(order.getCouponId())) {
            PayClient client = payClientFactory.getPayClient(order.getChannelId());
            try {
                PayCommonResult<PayQueryUnifiedRespDTO<ObjectNode>> result = client.unifiedQuery(PayQueryUnifiedReqDTO.builder()
                        .merchantOrderId(order.getMerchantOrderId())
                        .build());
                log.info("优惠券解锁{},查询支付结果:{}", payOrder.getId(), JsonUtils.toJsonString(result));
                if (result.isSuccess()) {
                    if (result.getData().getStatus() == PayStatusEnum.WAITING) {
                        if ("交易不存在".equals(result.getApiMsg())) {
                            log.info("交易不存在 {}, 释放优惠券", order.getMerchantOrderId());
                        } else if (order.getExpireTime() != null && order.getExpireTime().isBefore(LocalDateTime.now())) {
                            PayCommonResult<?> r = client.unifiedClose(PayCloseUnifiedReqDTO.builder().merchantOrderId(order.getMerchantOrderId()).build());
                            log.info("关闭订单 {}", JsonUtils.toJsonString(r));
                        } else {
                            couponUnlockDelayProducer.send(payOrder.getId());
                            return;
                        }
                    } else if (result.getData().getStatus() == PayStatusEnum.SUCCESS) {
                        return;
                    }
                }
            } catch (Exception e) {
                log.error("", e);
            }
            try {
                TenantUtils.execute(order.getMerchantId(), () -> {
                    CouponUnLockVo unlock = new CouponUnLockVo();
                    unlock.setIds(order.getCouponId());
                    log.info("优惠券解锁 {}", order.getCouponId());
                    CommonResult<Boolean> result = couponApi.couponUntieLock(unlock);
                    log.info("优惠券解锁结果 {}", JsonUtils.toJsonString(result));
                });
            } catch (Exception e) {
                log.error("解锁优惠券异常 {}", order.getCouponId());
            }
        }
    }
}
